/*

Copyright (C) 2000 - 2008 Christian Kreibich <christian@whoop.org>.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <netdb.h>

#include <nd.h>
#include <nd_gui.h>
#include <nd_raw_protocol.h>

#include "nd_tcp.h"
#include "nd_tcp_prefs.h"
#include "nd_tcp_callbacks.h"


static ND_ProtoField tcp_fields[] = {
  { ND_VAL_FIELD, N_("Src. port (%u)"),    N_("Source port number"),          16, nd_tcp_sport_cb   },
  { ND_VAL_FIELD, N_("Dst. port (%u)"),    N_("Destination port number"),     16, nd_tcp_dport_cb   },
  { ND_VAL_FIELD, N_("Seq. number (%lu)"), N_("Sequence number"),             32, nd_tcp_seq_cb     },
  { ND_VAL_FIELD, N_("Ack number (%lu)"),  N_("Acknowledgement number"),      32, nd_tcp_ack_cb     },
  { ND_VAL_FIELD, N_("Data offset (%u)"),  N_("Data offset (header length)"), 4,  nd_tcp_off_cb     },
  { ND_VAL_FIELD, N_("Unused (%u)"),       N_("Unused bits"),                 6,  nd_tcp_unused_cb  },
  { ND_FLG_FIELD, N_("U"),                 N_("Urgent flag"),                 1,  nd_tcp_u_cb       },
  { ND_FLG_FIELD, N_("A"),                 N_("ACK flag"),                    1,  nd_tcp_a_cb       },
  { ND_FLG_FIELD, N_("P"),                 N_("Push flag"),                   1,  nd_tcp_p_cb       },
  { ND_FLG_FIELD, N_("R"),                 N_("Reset flag"),                  1,  nd_tcp_r_cb       },
  { ND_FLG_FIELD, N_("S"),                 N_("SYN flag"),                    1,  nd_tcp_s_cb       },
  { ND_FLG_FIELD, N_("F"),                 N_("FIN flag"),                    1,  nd_tcp_f_cb       },
  { ND_VAL_FIELD, N_("Win (%u)"),          N_("TCP window size"),             16, nd_tcp_win_cb     },
  { ND_VAL_FIELD, N_("Checksum (0x%.4x)"), N_("Checksum"),                    16, nd_tcp_cksum_cb   },
  { ND_VAL_FIELD, N_("Urgent (%u)"),       N_("Urgent pointer"),              16, nd_tcp_urp_cb     },
  { 0, NULL, NULL, 0, NULL }
};


/* Field definitions for TCP options: */

static ND_ProtoField tcp_opt_fields[] = {
  { ND_VAL_FIELD, N_("Opt. (%s)"),        N_("IP option type"),             8,  nd_proto_8bit_cb   },
  { ND_VAL_FIELD, N_("Len. (%u)"),        N_("IP option length"),           8,  nd_proto_8bit_cb   },
  { ND_VAL_FIELD, "%u",                   N_("Maximum segment size"),       16, nd_proto_16bit_cb  },
  { ND_VAL_FIELD, "%u",                   N_("Window scaling shift count"), 8,  nd_proto_8bit_cb   },
  { ND_VAL_FIELD, N_("(%i bytes)"),       N_("Unknown option data"),        8,  NULL                     },
  { ND_VAL_FIELD, N_("%lu"),              N_("Timestamp value"),            32, nd_proto_32bit_cb  },
  { ND_VAL_FIELD, "%lu",                  N_("SAck left edge"),             32, nd_proto_32bit_cb  },
  { ND_VAL_FIELD, "%lu",                  N_("SAck right edge"),            32, nd_proto_32bit_cb  },
  { 0, NULL, NULL, 0, NULL }    
};


ND_MenuData tcp_menu_data[] = {
  { N_("Fix Checksums"), N_("Fixes the TCP checksums of the current selection"), 0, nd_tcp_cksum_fix_cb },
  { NULL, NULL, 0, NULL}
};


static LND_Protocol *tcp;
static ND_Protocol  *tcp_gui;


/* Plugin hook implementations: ---------------------------------------- */

const char *
name(void)
{
  return _("TCP Plugin");
}


const char *
description(void)
{
  return _("A plugin providing support for the TCP protocol.\n");
}


const char *
author(void)
{
  return ("Christian Kreibich, <christian@whoop.org>");
}


const char *
version(void)
{
  return VERSION_MAJOR;
}


LND_Protocol *
init(void)
{
  if (! (tcp = libnd_proto_registry_find(LND_PROTO_LAYER_TRANS, IPPROTO_TCP)))
    return NULL;

  tcp_gui = nd_proto_new(tcp);

  tcp_gui->create_gui    = nd_tcp_create_gui;
  tcp_gui->set_gui       = nd_tcp_set_gui;

  /* We're using a button table to display the protocol content,
     so we need to hook them in here: */
  tcp_gui->fields = tcp_fields;
  tcp_gui->header_width = 32;

  /* We provide a little menu that allows us to fix checksums. */
  tcp_gui->menu = nd_gui_create_menu(tcp_menu_data);
	     
  /* Hook TCP options into preferences dialog! */
  nd_tcp_init_prefs();  

  return tcp;
}


/* Protocol method implementations: ------------------------------------ */

GtkWidget *
nd_tcp_create_gui(LND_Trace *trace, LND_ProtoInfo *pinf)
{
  GtkWidget *table;

  table = nd_gui_proto_table_create(trace, pinf);

  return table;
}


void       
nd_tcp_set_gui(const LND_Packet *packet, LND_ProtoInfo *pinf)
{
  struct ip *iphdr;
  struct tcphdr *tcphdr;
  LND_ProtoData *pd;
  struct servent *serv;

  if (pinf->inst.nesting != 0)
    D(("WARNING -- TCP plugin doesn't support nested TCP\n"));

  if (!libnd_tcp_get_headers(packet, &iphdr, &tcphdr))
    return;
  
  nd_tcp_set_gui_sport(pinf, tcphdr);
  nd_tcp_set_gui_dport(pinf, tcphdr);
  nd_tcp_set_gui_seq(pinf, tcphdr);
  nd_tcp_set_gui_ack(pinf, tcphdr);
  nd_tcp_set_gui_off(pinf, tcphdr);
  nd_tcp_set_gui_unused(pinf, tcphdr);
  nd_tcp_set_gui_flags(pinf, tcphdr);
  nd_tcp_set_gui_win(pinf, tcphdr);
  nd_tcp_set_gui_cksum(pinf, iphdr, tcphdr, packet);
  nd_tcp_set_gui_urg(pinf, tcphdr);
  nd_tcp_set_gui_options(pinf, tcphdr, packet);

  /* Try to label the next tab appropriately if it's not a handled
   * protocol (e.g., "HTTP" is nicer than saying "(remaining)").
   *
   * First check if there actually is uninterpreted data and
   * TCP coming before it, and if we can then find a string
   * representation of the port number, replace the label of
   * the raw data displayer with that service name.
   */
  if (! (pd = libnd_packet_get_last_nonraw(packet)) || !libnd_packet_get_trace(packet))
    return;
  
  if (pd->inst.proto != tcp)
    return;

  serv = getservbyport(tcphdr->th_dport, "tcp");
  if (!serv)
    serv = getservbyport(tcphdr->th_sport, "tcp");

  if (serv)
    {
      ND_ProtoInfo *pinf_raw = nd_raw_proto_get_gui(libnd_packet_get_trace(packet));
      gtk_label_set_text(GTK_LABEL(pinf_raw->proto_label), serv->s_name);
    }
}



/* Misc helper stuff below --------------------------------------------- */

void  
nd_tcp_set_gui_sport(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[0], DATA_TO_PTR(ntohs(tcphdr->th_sport)));
}

void  
nd_tcp_set_gui_dport(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[1], DATA_TO_PTR(ntohs(tcphdr->th_dport)));
}

void  
nd_tcp_set_gui_seq(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[2], DATA_TO_PTR(ntohl(tcphdr->th_seq)));
}

void  
nd_tcp_set_gui_ack(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[3], DATA_TO_PTR(ntohl(tcphdr->th_ack)));
}

void  
nd_tcp_set_gui_off(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[4], DATA_TO_PTR(tcphdr->th_off));
}

void  
nd_tcp_set_gui_unused(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[5], DATA_TO_PTR(((tcphdr->th_x2 << 2) | ((tcphdr->th_flags & 0xc0) >> 6))));
}

void  
nd_tcp_set_gui_flags(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[6],  DATA_TO_PTR(tcphdr->th_flags & TH_URG));
  nd_proto_field_set(pinf, &tcp_fields[7],  DATA_TO_PTR(tcphdr->th_flags & TH_ACK));
  nd_proto_field_set(pinf, &tcp_fields[8],  DATA_TO_PTR(tcphdr->th_flags & TH_PUSH));
  nd_proto_field_set(pinf, &tcp_fields[9],  DATA_TO_PTR(tcphdr->th_flags & TH_RST));
  nd_proto_field_set(pinf, &tcp_fields[10], DATA_TO_PTR(tcphdr->th_flags & TH_SYN));
  nd_proto_field_set(pinf, &tcp_fields[11], DATA_TO_PTR(tcphdr->th_flags & TH_FIN));
}

void  
nd_tcp_set_gui_win(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[12], DATA_TO_PTR(ntohs(tcphdr->th_win)));
}

void  
nd_tcp_set_gui_cksum(LND_ProtoInfo *pinf, struct ip *iphdr,
		     struct tcphdr *tcphdr, const LND_Packet *packet)
{
  nd_proto_field_set(pinf, &tcp_fields[13], DATA_TO_PTR(ntohs(tcphdr->th_sum)));

  /* Show as "unknown" if we don't have the whole payload
   * or we somehow cannot know.
   */
  if ((guchar *)iphdr + ntohs(iphdr->ip_len) > libnd_packet_get_end(packet) ||
      libnd_packet_get_proto_index(packet, &pinf->inst) >
      libnd_packet_get_last_fixable_proto(packet))
    {
      nd_proto_info_field_set_state(pinf,
				    &tcp_fields[13],
				    ND_FIELD_STATE_UNKN);
      return;
    }

  if (!libnd_tcp_csum_correct(packet, NULL))
    nd_proto_info_field_set_state(pinf,
				  &tcp_fields[13],
				  ND_FIELD_STATE_ERROR);
  else
    nd_proto_info_field_set_state(pinf,
				  &tcp_fields[13],
				  ND_FIELD_STATE_NORMAL);
}

void  
nd_tcp_set_gui_urg(LND_ProtoInfo *pinf, struct tcphdr *tcphdr)
{
  nd_proto_field_set(pinf, &tcp_fields[14], DATA_TO_PTR(ntohs(tcphdr->th_urp)));
}


void
nd_tcp_set_gui_options(LND_ProtoInfo *pinf, struct tcphdr *tcphdr, const LND_Packet *packet)
{
  char         label[MAXPATHLEN];
  int          opts_len, o_len, opts_done, opts_done_old, i;
  guchar      *opts_p, *o_next;
  gboolean     is_error;

  nd_gui_proto_table_clear(libnd_packet_get_trace(packet), pinf);

  opts_len  = (tcphdr->th_off*4) - 20;
  opts_done = 0;
  opts_done_old = -1;

  if (opts_len == 0)
    return;

  while (opts_done < opts_len && opts_done != opts_done_old)
    {
      opts_done_old = opts_done;
      is_error = FALSE;
      opts_p = ((guchar *) tcphdr) + 20 + opts_done;
  
      switch(*opts_p)
	{
	case TCPOPT_EOL:
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("EOL"), FALSE);
	  opts_p++;
	  opts_done = opts_len;
	  break;

	case TCPOPT_NOP:
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("NOP"), FALSE);
	  opts_p++;
	  opts_done++;
	  break;

	case TCPOPT_MAXSEG:
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;
	  
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("MAXSEG"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[2], DATA_TO_PTR(htons(*(guint16*)opts_p)), is_error);
	  opts_p += 2;
	  break;

	case TCPOPT_WINDOW:
	  /*WSCALE is only allowed on SYN segments*/
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;
	  
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("WINDOW"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[3], DATA_TO_PTR(*(guchar *) opts_p), is_error);
	  opts_p += 2;
	  break;

	case TCPOPT_TIMESTAMP:
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;

	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("TS"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  for (i = 0; i < 2; i++)
	    {
	      nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[5], DATA_TO_PTR(ntohl(* (guint32*) opts_p)), is_error);
	      opts_p += 4;
	    }
	  break;	  

	case TCPOPT_SACK_PERMITTED:
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;

	  /* Sack-permitted is only allowed on SYNs,
	     so declare as erroneous when this is not a SYN: */
	  if ((tcphdr->th_flags & TH_SYN) == 0)
	    is_error = TRUE;
	  
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("SAck Perm"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  if (o_len > 2)
	    {
	      tcp_opt_fields[4].bits = (o_len * 8) - 16;
	      g_snprintf(label, MAXPATHLEN, tcp_opt_fields[4].label, o_len - 2);
	      /* This data isn't supposed to be here, so show as error: */
	      nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[4], DATA_TO_PTR(o_len - 2), TRUE);
	    }
	  break;

	case TCPOPT_SACK:
	  opts_p++;
	  o_len = *opts_p;
	  o_next = opts_p + o_len - 1;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;
	  
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("SAck"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  while (opts_p < o_next)
	    {
	      nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[6], DATA_TO_PTR(ntohl(*(guint32*) opts_p)), is_error);
	      opts_p += 4;
	      nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[7], DATA_TO_PTR(ntohl(*(guint32*) opts_p)), is_error);
	      opts_p += 4;
	    }
	  break;

	case 19: /* MD5 signature of BGP data, RFC 2385 */
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;
	  
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], _("MD5"), is_error);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  opts_p++;

	  tcp_opt_fields[4].bits = (o_len * 8) - 16;
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[4], DATA_TO_PTR(o_len - 2), is_error);
	  break;
	  
	default:
	  opts_p++;
	  o_len = *opts_p;
	  opts_done += o_len;

	  if (opts_done > opts_len)
	    break;

	  g_snprintf(label, MAXPATHLEN, "%u", *(opts_p - 1));
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[0], label, FALSE);
	  nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[1], DATA_TO_PTR(o_len), is_error);
	  
	  if (o_len > 2) 
	    {
	      tcp_opt_fields[4].bits = (o_len * 8) - 16;
	      nd_gui_proto_table_add(libnd_packet_get_trace(packet), pinf, &tcp_opt_fields[4], DATA_TO_PTR(o_len - 2), is_error);
	    }
	}
	  
      if (opts_done > opts_len)
	D(("Warning -- bogus TCP options. ...\n"));
    }      
}


LND_Protocol *
nd_tcp_get(void)
{
  return tcp;
}


ND_Protocol *
nd_tcp_get_gui(void)
{
  return tcp_gui;
}


